package com.dce.blockchain.web.controller;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.dce.blockchain.web.service.BlockService;
import com.dce.blockchain.web.service.PowService;
import com.dce.blockchain.web.util.BlockCache;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;



@Controller
public class BlockController {

    @Resource
    BlockService blockService;
    
    @Autowired
    BlockCache blockCache;

    @Resource
    PowService powService;
    
    /**
     * 查看当前节点区块信息
     * @return
     */
    @GetMapping("/scan")
    @ResponseBody
    public String scanBlock() {

        return JSON.toJSONString(blockCache.getBlockChain());
    }
    
    /**
     * 查看当前节点区块链交易数据
     * @return
     */
    @GetMapping("/data")
    @ResponseBody
    public String scanData() {
        return JSON.toJSONString(blockCache.getPackedTransactions());
    }


    /**
     * 创建创世区块
     * @return
     */
    @GetMapping("/create")
    @ResponseBody

    public ModelAndView createFirstBlock(ModelAndView model) {
        blockService.createGenesisBlock();
        String jsonData = JSON.toJSONString(blockCache.getBlockChain());
        model.addObject("jsonData", jsonData);
        //return new ModelAndView("forward:/index.html");
        model.setViewName("forward:/index.html");
        return model;

    }
    /**
     * 工作量证明PoW
     * 挖矿生成新的区块 
     */
    @GetMapping("/mine")
    @ResponseBody
    public String createNewBlock() {
        powService.mine();
        return JSON.toJSONString(blockCache.getBlockChain());
    }
     
}